<template>
  <view class="container">
    <!-- 加载状态 -->
    <scroll-view
        scroll-y
        lower-threshold="100"
        scroll-with-animation
        @scrolltolower="handleScrollToLower"
        :refresher-enabled="true"
        @refresherrefresh="handleComponentRefresh"
    >
      <!-- 加载状态 -->
      <view v-if="contentList.length === 0 " class="empty">
        <text>暂无数据</text>
      </view>

      <!-- 数据列表 -->
      <uni-list v-if="contentList.length > 0">
        <uni-list-item clickable
                       v-for="(item, index) in contentList"
                       :key="item.articleHref"
                       :title="item.articleTitle"
                       :note="item.articlePreface"
                       :time="item.articleTime"
                       :badge-text="item.articleEye.toString()"
                       @click="handleItemClick(item.articleHref)"
                       thumbSize="lg"
        >
          <!-- 替换左侧缩略图部分 -->
          <template   v-slot:header>
            <view class="thumb-wrapper">
              <image
                  :src="item.img"
                  mode="aspectFill"
                  class="custom-thumb"
                  @error="handleImageError(item)"
              lazy-load
              />
            </view>
          </template>
          <!-- 原有其他模板内容保持不变 -->
          <template v-slot:footer>
            <view class="custom-right">
              <text class="tag">{{ item.cloudTag }}</text>
              <uni-icons type="right" size="16"></uni-icons>
            </view>
          </template>
        </uni-list-item>
      </uni-list>
      <!-- 加载状态 -->
      <uni-load-more
          :status="isNoMore ? 'noMore' : isLoading ? 'loading' : 'more'"
          :icon-size="16"
          :content-text="{
          contentdown: '上拉加载更多',
          contentrefresh: '正在加载...',
          contentnomore: '已加载全部内容'
        }"
      />
    </scroll-view>
  </view>
</template>

<style>
.container {
  height: 100vh; /* 占满屏幕高度 */
  padding: 20rpx;
  background-color: #f5f5f5;
}

.loading, .empty {
  text-align: center;
  padding: 40rpx;
  color: #999;
}

/* 列表项样式 */
::v-deep .uni-list-item__container {
  padding: 24rpx !important;
  border-bottom: 1rpx solid #eee !important;
}

.custom-right {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.custom-right .tag {
  font-size: 24rpx;
  color: #666;
  padding: 4rpx 12rpx;
  background-color: #f0f0f0;
  border-radius: 20rpx;
}

::v-deep .uni-list-item__container {
  cursor: pointer; /* 移动端默认无光标，此属性仅对H5生效 */
}
scroll-view {
  height: 100vh; /* 确保容器占满屏幕 */
  overflow-anchor: none; /* 防止iOS自动调整 */
}
/* 缩略图容器 */
.thumb-wrapper {
  width: 100rpx; /* 固定宽度 */
  height: 60rpx; /* 固定高度 */
  border-radius: 8rpx;
  overflow: hidden;
  flex-shrink: 0; /* 防止压缩 */
  margin-right: 20rpx;
}

/* 图片样式 */
.custom-thumb {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 关键属性：保持比例填充容器 */
}

</style>

<script>
import {getContentList} from "@/api/homeContent.js";
import {throttle} from 'lodash-es';

export default {
  data() {
    return {
      contentList: [],
      loading: false,
      isLoading: false,
      currentPage: 1,    // 当前页码
      totalPages: 1,     // 总页数
      isNoMore: false,    // 是否没有更多数据
      scrollViewHeight: 600,
      reachBottomTimer: null,
      isRefreshing: false // 刷新状态
    };
  },
  mounted() {
    this.calculateScrollHeight();
    // 小程序环境监听窗口变化
    if (typeof uni.onWindowResize === 'function') {
      uni.onWindowResize(() => {
        this.calculateScrollHeight();
      });
    }
  },
  onLoad() {
    this.loadData();
  },
  methods: {
    async loadData() {
      console.info("loadData this.isLoading "+this.isLoading)
      if (this.isLoading) return; // 防止重复请求
      this.isLoading = true;
      this.loading = true;
      try {
        const res = await getContentList(this.currentPage, 10);
        console.info("res", res);
        if (res.code === '200') {
          if (this.currentPage === 1) {
            this.contentList = res.data.records; // 首次加载清空列表
          } else {
            this.contentList.push(...res.data.records); // 追加数据
          }
          console.info("contentList", this.contentList);
          // 更新分页信息（网页2的分页判断逻辑）
          this.totalPages = res.data.pages;
          this.isNoMore = this.currentPage >= this.totalPages;
        }
      } catch (err) {
        console.error('加载失败:', err);
        this.showErrorRetry(); // 封装错误处理
      } finally {
        this.loading = false;
        this.isLoading = false;
      }
    },

    //点击进入详情
    handleItemClick(id) {
      console.log("跳转ID:", id); // 调试是否获取到有效ID
      if (!id) {
        uni.showToast({title: '缺少文章ID', icon: 'none'});
        return;
      }
      uni.navigateTo({url: `/pages/index/blogInfo/detail?id=${id}`});
    },

    // 上拉触底事件
    // 移除防抖改用标志位
    handleScrollToLower: throttle(function() {
      console.info("handleScrollToLower this.loading"+this.loading+" this.isNoMore"+this.isNoMore)

      if (this.loading || this.isNoMore) return
      this.loading = true
      this.currentPage++
      console.info("handleScrollToLower this.currentPage"+this.currentPage)
      this.loadData().finally(() => {
        this.loading = false; // 确保加载完成后重置状态
      });
    }, 1000),

    //下拉刷新
    handleComponentRefresh() {
      console.info("handleComponentRefresh")
      this.isRefreshing = true;
      this.currentPage =1;
      const timer = setTimeout(() => {
        console.info("handleComponentRefresh stopPullDownRefresh")
        uni.stopPullDownRefresh();
      }, 10000); // 10秒超时
      this.loadData().finally(() => {
        clearTimeout(timer); // 清除超时
        this.isRefreshing = false;
        uni.stopPullDownRefresh();
      });
    },

    // 增强型错误处理
    async showErrorRetry() {
      const {confirm} = await uni.showModal({
        title: '加载失败',
        content: '是否重试？',
        confirmText: '重试'
      });
      if (confirm) this.loadData();
    },


    calculateScrollHeight() {
      if (process.env.VUE_APP_PLATFORM === 'h5') {
        const query = uni.createSelectorQuery().in(this);
        query.select('.container').boundingClientRect(data => {
          if (data && data.height > 0) {
            this.scrollViewHeight = data.height - uni.upx2px(50) // 转换rpx
          } else {
            this.scrollViewHeight = window.innerHeight * 0.8 // 默认高度
          }
        }).exec();
      }
    },

    // 图片加载失败处理
    handleImageError(item) {
      console.warn('图片加载失败:', item.img)
      // 可设置默认图或隐藏元素
      this.$set(item, 'img', '/src/static/logo.png')
    }

  }
}
</script>
